package com.book.modules.aspect;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.book.common.api.entity.CurrentUser;
import com.book.common.helper.I18nHelper;
import com.book.modules.annotation.Permissions;
import com.book.modules.enums.Logical;
import com.book.modules.exception.OauthException;
import com.book.modules.helper.CurrentUserHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.List;

/**
 * Description： OAuth菜单权限控制
 *
 * @Author： leo.xiong
 * @CreateDate： 2019/8/13 16:29
 * @Email： leo.xiong@suyun360.com
 * Version：1.0
 */
@Slf4j
@Aspect
@Component
public class OauthPermissionAspect {

    @Autowired
    private CurrentUserHelper currentUserHelper;

    @Autowired
    private I18nHelper i18nHelper;

    @Pointcut("@annotation(com.book.modules.annotation.Permissions)")
    public void pointcut() {
        // do nothing
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Permissions permissionsAnnotation = method.getAnnotation(Permissions.class);
        if (permissionsAnnotation == null) {
            return point.proceed();
        }
        String[] values = permissionsAnnotation.value();
        if (values.length == 0) {
            return point.proceed();
        }
        String value = StringUtils.join(values, StringPool.COMMA);
        CurrentUser currentUser = currentUserHelper.getCurrentUser();
        if (currentUser == null) {
            throw new OauthException(i18nHelper.get("BOOK:CORE:10004"));
        }
        List<String> permissionList = currentUser.getPermissionList();
        int equalSize = 0;
        for (String permission : permissionList) {
            if (value.contains(permission)) {
                equalSize++;
            }
        }
        if (Logical.AND.equals(permissionsAnnotation.logical()) && equalSize != values.length) {
            throw new OauthException(i18nHelper.get("BOOK:CORE:10003"));
        } else if (equalSize == 0) {
            throw new OauthException(i18nHelper.get("BOOK:CORE:10003"));
        }
        return point.proceed();
    }
}
